// utils/location.js
export default {
	// 检查系统定位是否开启
	checkSystemLocation() {
		return new Promise((resolve) => {
			uni.getSystemSetting({
				success: (res) => {
					resolve(res.locationEnabled)
				},
				fail: () => resolve(false)
			})
		})
	},

	// 检查小程序定位权限
	checkAppLocationPermission() {
		return new Promise((resolve) => {
			uni.getSetting({
				success: (res) => {
					resolve(res.authSetting['scope.userLocation'])
				},
				fail: () => resolve(null)
			})
		})
	},

	// 获取当前位置
	getCurrentPosition() {
		return new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'wgs84',
				altitude: true,
				success: resolve,
				fail: reject
			})
		})
	},

	// 显示打开系统定位提示
	showOpenSystemLocationModal() {
		return new Promise((resolve) => {
			uni.showModal({
				title: '需要开启定位服务',
				content: '请在手机设置中开启定位服务',
				confirmText: '去设置',
				success: (res) => {
					if (res.confirm) {
						uni.openSystemLocationSetting()
					}
					resolve()
				}
			})
		})
	},

	// 显示打开小程序权限设置提示
	showOpenAppSettingModal() {
		return new Promise((resolve) => {
			uni.showModal({
				title: '需要位置权限',
				content: '请授权位置权限以使用该功能',
				confirmText: '去授权',
				success: (res) => {
					if (res.confirm) {
						uni.openSetting({
							success: (settingRes) => {
								resolve(settingRes.authSetting['scope.userLocation'] ===
									true)
							},
							fail: () => resolve(false)
						})
					} else {
						resolve(false)
					}
				}
			})
		})
	},

	// 主方法：获取定位
	async getLocation() {
		try {
			// 1. 检查系统定位
			const systemEnabled = await this.checkSystemLocation()
			if (!systemEnabled) {
				await this.showOpenSystemLocationModal()
				throw new Error('系统定位未开启')
			}

			// 2. 检查小程序权限
			const authStatus = await this.checkAppLocationPermission()
			if (authStatus === false) {
				const granted = await this.showOpenAppSettingModal()
				if (!granted) {
					throw new Error('用户拒绝授权')
				}
			}

			// 3. 获取位置
			const location = await this.getCurrentPosition()
			return {
				latitude: location.latitude,
				longitude: location.longitude,
				altitude: location.altitude || 0
			}

		} catch (error) {
			console.error('获取定位失败:', error)
			throw error
		}
	}
}